#include "GameThread.h"

#include <iostream>
#include <SDL/SDL.h>

using std::cout;
using std::cerr;
using std::endl;


GameThread::GameThread():
	Thread("GameThread")
{
	cout << "constr" << endl;
}

GameThread::~GameThread()
{
	cout << "destr" << endl;
}


void GameThread::init()
{
	cout << "init" << endl;
	prevtime = 0;
	nowtime  = 0;

	framerate = 2; // 100;
	frametime = 1000 / framerate;
}


void GameThread::run()
{
	// store starting time
	prevtime = SDL_GetTicks();

	// TODO: perform one frame
	static int i = 0;
	cout << "run" << i << endl;
	i++;


	// time the frames
	nowtime  = SDL_GetTicks();
	int timespent = nowtime   - prevtime;
	int timeleft  = frametime - timespent;
	if(timeleft > 5)
	{
		if(timeleft > frametime)
		{
			cerr << "timeleft is too large!" << endl;
			timeleft = frametime;
		}
		SDL_Delay(timeleft);
	}
	cout << prevtime << ", " << nowtime << ", "  << frametime << ", " << timespent << ", " << timeleft << endl;

}


void GameThread::shutDown()
{
	cout << "shutDown" << endl;
}




///*
// * Entry point for drawing thread.
// */
//int drawThreadMain(void *)
//{
//	trace << "TODO: initialize drawing thread data here" << endl;
//	while(!isQuitting())
//	{
//		cout << "TODO: redraw screen continuously here" << endl;
//		//SDL_GL_SwapBuffers();
//		SDL_Delay(1000);
//	}
//	trace << "TODO: destroy drawing thread data here" << endl;
//	return 0;
//}
